package com.ideafactory.client.ybservice;

import android.app.AlarmManager;
import android.app.Dialog;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ideafactory.client.afinal.NetConstants;
import com.ideafactory.client.beans.CatalogGoodsBean;
import com.ideafactory.client.beans.OrderBaseInfoBean;
import com.ideafactory.client.beans.OrderGoodsBean;
import com.ideafactory.client.print.icod.IcodPrinterManager;
import com.ideafactory.client.utils.FileConstants;
import com.ideafactory.client.utils.FileUtils;
import com.ideafactory.client.utils.GlideImageLoader;
import com.ideafactory.client.utils.JsonForBean;
import com.ideafactory.client.utils.SpUtils;
import com.ideafactory.client.utils.ViewUtil;
import com.ideafactory.client.utils.ViewUtil2;
import com.ideafactory.client.utils.netutils.MyCallBack;
import com.ideafactory.client.utils.netutils.NetUtils;
import com.ideafactory.client.views.CameraView;
import com.ideafactory.client.views.FullVideoView;
import com.ideafactory.client.ybselfservice.R;
import com.ideafactory.client.ybservice.ybviewpager.CompanyInforPager;
import com.ideafactory.client.ybservice.ybviewpager.CompanyVideoPager;
import com.ideafactory.client.ybservice.ybviewpager.GoodsBasePager;
import com.ideafactory.client.ybservice.ybviewpager.TeamInforPager;
import com.lidroid.xutils.BitmapUtils;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;

import org.json.JSONException;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;
import top.zibin.luban.OnRenameListener;

import static android.content.Context.LAYOUT_INFLATER_SERVICE;
import static com.baidu.location.h.i.r;
import static com.ideafactory.client.ybselfservice.R.id.iv_campusScenery;
import static com.ideafactory.client.ybselfservice.R.id.lauout_info;
import static com.ideafactory.client.ybselfservice.R.id.layout_product;
import static com.ideafactory.client.ybselfservice.R.id.rb_china;
import static com.ideafactory.client.ybselfservice.R.id.rb_england;
import static com.ideafactory.client.ybselfservice.R.id.rb_th;
import static com.ideafactory.client.ybselfservice.R.id.videoView_haibao;
import static com.ideafactory.client.ybselfservice.R.layout.dialog;
import static com.ideafactory.client.ybservice.ybviewpager.GoodsBasePager.GOODS_DETIAL_INT;
import static com.ideafactory.client.ybservice.ybviewpager.GoodsBasePager.MAIN_FRAGMENT;

/**
 * Created by LiuShao on 2016/5/24.
 */
@ContentView(R.layout.activity_main)
public class MainFragment extends YbBaseFragment {
    private static final String TAG = "MainFragment";

    @ViewInject(R.id.iv_finger_animation)
    private ImageView iv_finger_animation;

    @ViewInject(R.id.edit_input2)
    private TextView edit_input2;

    @ViewInject(R.id.btn_clear)
    private Button btn_clear;

    @ViewInject(R.id.btn_back)
    private Button btn_back;

    @ViewInject(R.id.btn_ticket)
    private Button btn_ticket;

    @ViewInject(R.id.layout_ticket)
    private LinearLayout layout_ticket;

    @ViewInject(R.id.btn_back_main)
    private Button btn_back_main;

    @ViewInject(R.id.imageView)
    private ImageView imageView;

    @ViewInject(R.id.videoView)
    private VideoView videoView;





    int[] buttons;      //数字按钮数组
    String str1;               //旧输入值
    Button temp;

    private File path;

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        startFingerAnimation();


        Log.e("执行顺序", "MainFragment_onActivityCreated");
        initButton();
        initData();
    }




    @Override
    public void onStart() {
        super.onStart();
    }

    private OrderBaseInfoBean baseInfoBean = null;
    private JSONArray jsonArray;

    File fileNew;
    private List<OrderGoodsBean> mList = null;
    @Event(value = {R.id.btn_clear, R.id.btn_back, R.id.btn_ticket, R.id.btn_back_main})
    private void getTicket(View view) {
        switch (view.getId()) {
            case R.id.btn_clear:
                edit_input2.setText("");
                break;
            case R.id.btn_back:
                String str = edit_input2.getText().toString().trim();
                if (str.length() > 0) {
                    str1 = str.substring(0, str.length() - 1);
                    edit_input2.setText(str1);
                }
                break;
            case R.id.btn_ticket:
                Map map=new HashMap();
                String  orderCode=edit_input2.getText().toString().trim();
                if (orderCode.length()==8){

                    String exitPwd= SpUtils.getString(getActivity(), SpUtils.EXITPASSWORD, null);
                    Log.e(TAG, "exitPwd---------> "+exitPwd );
                    if (exitPwd!=null&&orderCode.equals(exitPwd)){
                        getActivity().finish();
                        return;
                    }
                }
                map.put("orderCode",orderCode);
                edit_input2.setText("");
                NetUtils.Post(NetConstants.SCANLETICKET, map, new MyCallBack<String>() {
                    @Override
                    public void onSuccess(String result) {

                        JSONObject jsonObject = JSON.parseObject(result);
                        System.out.println("MainLayout---result---->"+result);
                        jsonArray = jsonObject.getJSONArray("goodList");
                        baseInfoBean = JsonForBean.getPerson(jsonObject.getString("busSelfOrder"), OrderBaseInfoBean.class);
                        mList = JsonForBean.getPersonList(jsonArray.toString(), OrderGoodsBean.class);
                        if(mList!=null&&mList.size()>0){
                            layout_ticket.setVisibility(View.VISIBLE);
                            String path = FileConstants.CAllNumQR_CACHE_PATH;
                            File file = new File(path);
                            if (file.exists() == false) {
                                file.mkdirs();
                            }
                            String filepath = path + "cash2.jpg";
                            fileNew = new File(filepath);
                            if (fileNew.exists()) {
                                file.delete();
                            }
                            NetUtils.DownLoadFile(baseInfoBean.getOrderCodeUrl(), filepath, new MyCallBack<File>() {
                                @Override
                                public void onSuccess(File result) {
                                    Log.e("下载成功","");
                                    try {
                                        String shopName = SpUtils.getString(getActivity(), SpUtils.SHOP_NAME, "");
                                        String shopAddress = SpUtils.getString(getActivity(), SpUtils.SHOP_ADDRESS, "");
                                        InputStream cashIn = new FileInputStream(fileNew);
                                        File file = new File(FileConstants.SHOPIMG_CACHE_PATH + "shopimg.jpg");
                                        InputStream is = new FileInputStream(file);

                                        double realMoney=0d;

                                        for (int i = 0; i <mList.size() ; i++) {
                                            realMoney=realMoney+mList.get(i).getPrice()*mList.get(i).getCount();
                                        }

                                        realMoney=realMoney+baseInfoBean.getPackMoney();

                                        int isPrint = SpUtils.getInt(getActivity(), SpUtils.ISPRINT, 0);
                                        Log.e(TAG, "isPrint-------------->" + isPrint);
                                        if (isPrint == 1) {

                                            YbSelfService.printSeatTest(mList,YbSelfService.mUsbDev1,shopName, shopAddress, baseInfoBean.getAllMoney() + "", baseInfoBean.getOrderCallNum(),baseInfoBean.getPackMoney()+"",baseInfoBean.getIsPack(),baseInfoBean.getPreMoney()+"",realMoney+"");
                                            IcodPrinterManager.getIns().printText(mList,YbSelfService.mUsbDev1,shopName, shopAddress, baseInfoBean.getAllMoney() + "", baseInfoBean.getOrderCallNum(),baseInfoBean.getPackMoney()+"",baseInfoBean.getIsPack(),baseInfoBean.getPreMoney()+"",realMoney+"");

                                        }


//                                        YbSelfService.printerUtils.printerShop(mList, shopName, shopAddress, baseInfoBean.getAllMoney() + "", cashIn, baseInfoBean.getOrderCallNum(),baseInfoBean.getPackMoney()+"",baseInfoBean.getIsPack());
//                                        cashIn.close();
//                                        is.close();
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }

                                @Override
                                public void onError(Throwable ex, boolean isOnCallback) {
                                    super.onError(ex, isOnCallback);
                                    try {
                                        String shopName = SpUtils.getString(getActivity(), SpUtils.SHOP_NAME, "");
                                        String shopAddress = SpUtils.getString(getActivity(), SpUtils.SHOP_ADDRESS, "");
                                        File file = new File(FileConstants.SHOPIMG_CACHE_PATH + "shopimg.jpg");
                                        InputStream is = new FileInputStream(file);
//                                        YbSelfService.printerUtils.printerShop(mList,shopName, shopAddress, baseInfoBean.getAllMoney() + "", null, baseInfoBean.getOrderCallNum(),baseInfoBean.getPackMoney()+"",baseInfoBean.getIsPack());


                                        is.close();
                                        Log.e("下载","失败！！！！！");
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }

                                }
                            });


                            HashMap map = new HashMap();
                            String sb = SpUtils.getString(APP.getAPP(), SpUtils.DEVICENO, "");
                            map.put("deviceId", sb);
                            map.put("orderId", baseInfoBean.getId() + "");
                            NetUtils.Post(NetConstants.SCANLERETURN, map, new MyCallBack<String>() {
                                @Override
                                public void onSuccess(String result) {
                                    super.onSuccess(result);
                                    Log.e(TAG, "onSuccess: " );
                                }

                                @Override
                                public void onError(Throwable ex, boolean isOnCallback) {
                                    super.onError(ex, isOnCallback);
                                    Log.e(TAG, "onError: ");
                                }
                            });

                        }else{
                            System.out.println(mList.size());
                            Toast.makeText(APP.getAPP(),APP.getAPP().getResources().getString(R.string.input_error_tip),Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onError(Throwable ex, boolean isOnCallback) {
                        Toast.makeText(APP.getAPP(),"取票码不正确，请重新输入！",Toast.LENGTH_SHORT).show();

                        System.out.println("MainLayout---result---->"+"失败！！！！！");
//                        System.out.println("失败————————————》"+ex.getMessage().toString());
                    }
                });

                break;
            case R.id.btn_back_main:
                layout_ticket.setVisibility(View.GONE);
                edit_input2.setText("");
                break;
        }
    }


    public void initButton() {//初始化控件资源
        buttons = new int[]
                {       //记录数值按钮的id
                        R.id.btn_0, R.id.btn_1, R.id.btn_2, R.id.btn_3, R.id.btn_4,
                        R.id.btn_5, R.id.btn_6, R.id.btn_7, R.id.btn_8, R.id.btn_9
                };

        for (int i = 0; i < buttons.length; i++) {
            temp = (Button) this.getView().findViewById(buttons[i]);
            temp.setOnClickListener(
                    new View.OnClickListener() {                     //内部类
                        @Override
                        public void onClick(View v)    //重写方法
                        {
                            str1 = edit_input2.getText().toString().trim();    //得到textview中的字符串
                            str1 = str1 + String.valueOf(((Button) v).getText());
                            edit_input2.setText(str1);
                        }
                    }
            );
        }
    }

    private void initData() {
       String[] strings= SpUtils.getSharedPreference("strs");
       String playTime= SpUtils.getString(APP.getAPP(),"playTime",null);
        layout.setBackgroundResource(R.mipmap.mainbg_moren);
        if (strings!=null&&playTime!=null){
            addVideoAndImage(strings,playTime);
        }
    }


    @ViewInject(R.id.layout)
    private LinearLayout layout;

    private void addVideoAndImage(final String[] strings, final String playtime) {
        String path = FileConstants.VIDEO_CACHE_PATH;
       final Double playTime = Double.parseDouble(playtime);
        for (int i = 0; i <strings.length ; i++) {
            Log.e(TAG, "strings------> "+strings[i]);
            int index = strings[i].lastIndexOf("/");
            String str = strings[i].substring(index + 1, strings[i].length());
            String filepath = path + str;
           final File file=new File(filepath);
            Log.e(TAG, "file---->"+i+"-------->"+file.toString() );
            if (file.exists()&&!mAdlist.contains(file)){
                if (!file.isDirectory()){
                    mAdlist.add(file);
                    Log.e(TAG, "添加文件------------> "+ file.toString());
                }

            }else if (!file.exists()){
                NetUtils.DownLoadFile(strings[i], filepath, new MyCallBack<File>(){
                    @Override
                    public void onSuccess(File result) {
                        mAdlist.add(file);
                        handler.removeMessages(1);
                        Message msg=new Message();
                        msg.what=1;
                        msg.arg1=0;
                        msg.arg2=playTime.intValue();
                        handler.handleMessage(msg);
                        Log.e(TAG, "DownLoadFile --------->下载！ " );
                    }

                    @Override
                    public void onError(Throwable ex, boolean isOnCallback) {
                        Log.e(TAG, "onError: ----------------->"+ex.getMessage() );
                        super.onError(ex, isOnCallback);
                    }
                });
            }
        }
        if (mAdlist.size()>0){
            Message msg=new Message();
            msg.what=1;
            msg.arg1=0;
            msg.arg2=playTime.intValue();
            handler.handleMessage(msg);
        }
    }



    private int position;
    private List<File> mAdlist=new ArrayList<>();
    private Handler handler=new Handler() {
        @Override
        public void handleMessage(Message msg) {

            switch (msg.what) {
                case 1:
                    position = msg.arg1;
                    position = position % mAdlist.size();
                    Log.e(TAG, "position------> "+position );
                    Log.e(TAG, "mAdlist.size()------> "+mAdlist.size() );
                   final int playtime= msg.arg2;
                    File file=mAdlist.get(position);
                    if (FileUtils.isVideo(file.toString())) {
                        imageView.setVisibility(View.GONE);
                        videoView.setVisibility(View.VISIBLE);
                        imageView.setBackgroundColor(getResources().getColor(R.color.black));
                        layout.setBackgroundColor(Color.parseColor("#000000"));//正常的
                        videoView.setVideoPath(file.toString());
                        videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                            @Override
                            public void onPrepared(MediaPlayer mp) {
                                videoView.start();
                                Log.e("videoview", "onPrepared: ");
                            }
                        });
                        videoView.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                            @Override
                            public boolean onError(MediaPlayer mp, int what, int extra) {
                                Message msg = new Message();
                                msg.what = 1;
                                msg.arg1 = position + 1;
                                msg.arg2=playtime;
                                handler.sendMessage(msg);
                                Log.e("videoview", "onError: ");
                                return true;
                            }
                        });
                        videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                            @Override
                            public void onCompletion(MediaPlayer mp) {
                                Message msg = new Message();
                                msg.what = 1;
                                msg.arg1 = position + 1;
                                msg.arg2=playtime;
                                handler.sendMessage(msg);
                                Log.e("videoview", "onCompletion: ");

                            }
                        });
                    } else {
                        layout.setBackgroundColor(Color.parseColor("#000000"));//正常的
                        imageView.setVisibility(View.VISIBLE);
                        imageView.setScaleType(ImageView.ScaleType.FIT_XY);
                        videoView.setVisibility(View.GONE);
                        try {
                            imageView.setBackground(null);
                            layout.setBackground(imageView.getDrawable());
                            x.image().bind(imageView, file.toString());
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                        Message msg2 = new Message();
                        msg2.what = 1;
                        msg2.arg1 = position + 1;
                        msg2.arg2=playtime;
                        this.sendMessageDelayed(msg2, playtime*1000);
                    }
                    break;
            }
        }

    };







    @Event(value = {R.id.tv_jump_to_next, R.id.iv_finger_animation, R.id.layout})
    private void jumpToNext(View view) {
        Log.e("执行顺序", "MainFragment_jumpToNext");
        handler.removeMessages(1);
        if (((YbSelfService) getActivity()).toNextPager != null) {
            ((YbSelfService) getActivity()).toNextPager.toNext(YbSelfService.detialPosition);
            if (GoodsBasePager.onPagerChange != null) {
                GoodsBasePager.onPagerChange.changePositon(GoodsBasePager.MAIN_FRAGMENT, GoodsBasePager.GOODS_DETIAL_INT);
            }
        }
    }


    @Override
    public void onPause() {
        super.onPause();
        handler.removeMessages(1);

    }

    /**
     * 开启手指动画
     */
    private void startFingerAnimation() {
        Animation animation = new ScaleAnimation(1.0f, 1.1f, 1.0f, 1.1f,
                Animation.RELATIVE_TO_SELF, 0.5f,
                Animation.RELATIVE_TO_SELF, 0.5f);
        animation.setRepeatCount(-1);
        animation.setDuration(500);
        animation.setRepeatMode(Animation.REVERSE);
        iv_finger_animation.clearAnimation();
        iv_finger_animation.startAnimation(animation);
    }

    @Override
    public void onDestroyView() {
        layout.removeAllViews();
        layout.removeAllViewsInLayout();
        super.onDestroyView();
        Log.e("执行顺序", "MainFragment_onDestroyView");
    }


}
